﻿// Sequin.WebLogs.IpAddressSet
//
// (c) 2011 Arthur Pitman
//
// Part of the Sequin Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License (Version 2.1) as published by the Free Software Foundation.
// 
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public
// License (Version 2.1) along with this library; if not, write to the 
// Free Software Foundation, Inc., 
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
// or see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Sequin.WebLogs
{
	/// <summary>
	/// A simple class for reading a set of IPAddress instances from a file
	/// </summary>
	public class IPAddressSet
	{
		/// <summary>
		/// Reads a set of <see cref="IPAddress"/> instances from a file
		/// </summary>
		/// <param name="filename">Filename to read from</param>
		/// <returns>A hash set of <see cref="IPAddress"/> instances</returns>
		public static HashSet<IPAddress> FromFile(string filename)
		{
			var ips = new HashSet<IPAddress>();

			// open and read through each line in the file
			StreamReader reader = File.OpenText(filename);
			while (true)
			{
				try
				{
					string line = reader.ReadLine();
					if (line == null)
						break;

					// skip blank lines
					line = line.Trim();
					if (line.Length == 0)
						continue;

					// ignore any line starting with '#'
					if (line.StartsWith("#"))
						continue;

					// add each IP address
					IPAddress ip = IPAddress.Parse(line.Trim());
					ips.Add(ip);
				}
				catch (Exception e)
				{
					Console.Error.WriteLine(e.ToString());
				}
			}
			reader.Close();
			return ips;
		}

		/// <summary>
		/// Writes a set of <see cref="IPAddress"/> instances to a file
		/// </summary>
		/// <param name="ipAddresses">The <see cref="IPAddress"/> instances</param>
		/// <param name="filename">The filename</param>
		public static void WriteToFile(IEnumerable<IPAddress> ipAddresses, string filename)
		{
			var writer = File.CreateText(filename);
			foreach (var ipAddress in ipAddresses)
				writer.WriteLine(ipAddress.ToString());
			writer.Close();
		}
	}
}
